<?php
//
namespace app\home\controller;

use app\common\model\ShopGoodsBrandModel;
use app\common\model\ShopGoodsDataModel;
use app\common\model\ShopGoodsExtendModel;
use app\common\model\ShopGoodsGevalModel;
use app\common\model\ShopGoodsModel;
use app\common\model\ShopGoodsSkuModel;
use think\Db;
use think\Hook;
use think\Request;

class GoodsController extends BaseController
{

    private $goodsCategory;
    private $goodsModel;
    private $goodsSkuModel;
    private $goodsDataModel;
    private $goodsExtendModel;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->goodsCategory    = goods_cache_cat();
        $this->goodsModel       = new ShopGoodsModel();
        $this->goodsSkuModel    = new ShopGoodsSkuModel();
        $this->goodsDataModel   = new ShopGoodsDataModel();
        $this->goodsExtendModel = new ShopGoodsExtendModel();
        $this->brandModel       = new ShopGoodsBrandModel();
    }

    /*
     * 频道页
     */
    public function channel()
    {
        $cid        = $this->request->param('cid/d');
        $currentCat = $this->getCatInfo($cid);
        $this->assign('currentCat', $currentCat);
        return $this->fetch($currentCat['cat_tpl']);
    }

    /*
     * 列表页
     */
    public function itemlist()
    {
        $cid                            = $this->request->param('cid/d');
        $p1                             = $this->request->param('p1');
        $p2                             = $this->request->param('p2');
        $extendQuery['promotion_type']  = 0; //普通商品
        $currentCat                     = $this->getCatInfo($cid);
        $itemSearch                     = $this->request->param('item_search');
        //排序
        $p1 = empty($p1)?'goods_sort':$p1;
        $p2 = empty($p2)?'asc':$p2;
        $order              = "{$p1} {$p2}";
        //品牌搜索
        $brandIds = $this->request->param('brand');
        if (!empty($brandIds)) {
            $extendQuery['brand_id'] = ['in', $brandIds];
        }
        //多维检索 需前端自行设置如：型号|3代B,重量|100g这样得cookie数据格式
        if (!empty($itemSearch)) {
            $item        = explode(',', $itemSearch);
            $havingCount = count($item); //条件数
            foreach ($item as $k => $v) {
                $s               = explode('|', $v);
                $sqls[]          = "select cid,item_name,item_select,goods_id from shop_goods_extend where (item_name='{$s[0]}' and `item_select`='{$s[1]}')";
                $selected[$s[0]] = $s[1];
            }
            $sql      = '(' . implode(' UNION ', $sqls) . ')';
            $goodsIds = Db::table($sql . ' temp')->group('goods_id')->having("count('goods_id')={$havingCount}")->column('goods_id');
            if ($goodsIds) {
                $extendQuery['t1.goods_id'] = ['in', $goodsIds];
            }
            $extendSearch['item_search'] = $itemSearch;
        }
        $itemList       = goods_page_list($cid, '12', $extendQuery, $extendSearch, $order);
        $itemSearchList = get_cid_search($cid); //检索条件
        //匹配当前选中
        if (!empty($itemSearchList)) {
            foreach ($itemSearchList as $k => $v) {
                $v['selected']      = $selected[$v['item_name']];
                $itemSearchList[$k] = $v;//加入当前搜索条件
            }
        }
        if ($this->request->isAjax()) {
            return $itemList;
        }
        //获取品牌列表
        $brandList = get_brand_cid($cid);
        $this->assign('brandList', $brandList);
        $this->assign('itemList', $itemList);
        $this->assign('itemSearchList', $itemSearchList);
        $this->assign('extendSearch', $extendSearch);
        return $this->fetch($currentCat['cat_tpl']);
    }

    /**
     * 普通商品内容页
     */
    public function item()
    {
        $skuId                       = $this->request->param('sku_id/d');
        $skuInfo                     = $this->goodsSkuModel->find($skuId)->toArray();
        $goodsInfo                   = $this->goodsModel->getInfo($skuInfo['goods_id']);
        $goodsExtendList = [];
        if ($goodsInfo['extend_id'] > 0) {
            $goodsExtendList = $this->goodsExtendModel->where('goods_id', $skuInfo['goods_id'])->order('item_sort')->select()->toArray();
        }
        if(!empty($goodsInfo['brand_id'])){
            $goodsInfo['brandInfo']   = $this->brandModel->get($goodsInfo['brand_id'])->toArray();
            $goodsInfo['brandInfo']   = format_brand_content($goodsInfo['brandInfo']);
        }
        $goodsInfo['attr']        = goods_sku_name($goodsInfo);
        $goodsInfo['extend_list'] = $goodsExtendList;
        $goodsInfo                = array_merge($goodsInfo, $skuInfo);
        $goodsInfo                = format_goods_content($goodsInfo);
        $this->getCatInfo($goodsInfo['cid']);
        //计算商品各类型评价数量
        $goodsInfo['static_geval'] = $this->staticGeval($goodsInfo['goods_id']);
        //组装前端SKU数据
        if($goodsInfo['is_attr']==1){
            $skuItems     = goods_all_list($goodsInfo['site_id'], $goodsInfo['cid'], 99, ['goods_id'=>$goodsInfo['goods_id']], 'goods_sort desc,t1.goods_id desc');
            $skuList = [];
            foreach($skuItems as $v){
                $skuList[]=[
                    'sku_key'=>str_replace(',',';',$v['sku_name']),
                    'sku_id'=>$v['sku_id'],
                    'sku_sn'=>$v['sku_sn'],
                    'goods_id'=>$v['goods_id'],
                    'market_price'=>$v['market_price'],
                    'goods_price'=>$v['goods_price'],
                    'price'=>$v['simple_price'],
                    'goods_stock'=>$v['goods_stock'],
                    'goods_weight'=>$v['goods_weight'],
                    'min'=>$v['minimum'],
                    'fulltitle'=>$v['fulltitle'],
                    'goods_name'=>$v['goods_name'],
                    'sku_name'=>$v['sku_name'],
                    'step'=>$v['step'],
                ];
            }
            $this->assign('skuList',json_encode($skuList));
        }
        //dump($goodsInfo);
        /*评论数量*/
        $gevalcount=$this->staticGeval($goodsInfo['goods_id']);
        $this->assign('keyword', $goodsInfo['keywords']);
        $this->assign('description', $goodsInfo['description']);
        $this->assign('goodsInfo', $goodsInfo);
        $this->assign('gevalcount', $gevalcount);
        //hook浏览数据
        $params = ['uid'=>$this->getMemberUid(), 'goods_id'=>$goodsInfo['goods_id'],'sku_id'=>$goodsInfo['sku_id']];
        Hook::exec('app\\common\\behavior\\Home','goodsItem',$params);
        return $this->fetch($goodsInfo['content_tpl']);
    }

    /*
     * 搜索页
     */
    public function search()
    {
        $extendQuery                = [];
        $extendSearch               = [];
        $extendSearch['goods_name'] = $this->request->param('goods_name');
        if (!empty($extendSearch['goods_name'])) {
            $extendQuery['goods_name'] = ['like', "%{$extendSearch['goods_name']}%"];
        }
        $itemList = goods_page_list(0, 0, '12', $extendQuery);
        foreach ($itemList as $key => $item) {
            $itemList[$key]['goods_name']  = str_replace($extendSearch['goods_name'], '<span style="color:red">' . $extendSearch['goods_name'] . '</span>', $item['goods_name']);
            $itemList[$key]['description'] = str_replace($extendSearch['title'], '<span style="color:red">' . $extendSearch['title'] . '</span>', $item['description']);
        }
        if ($this->request->isAjax()) {
            return $itemList;
        }
        $this->assign('keyword', $this->webconfig['KEYWORDS']);
        $this->assign('description', $this->webconfig['DESCRIPTION']);
        $this->assign('itemList', $itemList);
        return $this->fetch();
    }

    /**
     * 根据栏目Id获取通用信息
     * @param $cid
     */
    private function getCatInfo($cid)
    {
        if (!is_numeric($cid)) {
            $this->error('参数错误！');
        }
        $currentCat  = $this->goodsCategory[$cid]; //当前栏目
        $locationCat = goods_location($cid); //当前位置
        if ($currentCat['is_son'] == true) {
            $selfCat = goods_cat_list('self', $cid); //取当前同级
            $sonCat  = goods_cat_list('son', $cid); //取当前下级
        } else {
            $selfCat = goods_cat_list('self', $cid); //取当前同级
            $sonCat  = []; //取当前下级
        }
        $this->assign('keyword', $currentCat['cat_keywords']);
        $this->assign('description', $currentCat['cat_description']);
        $this->assign('currentCat', $currentCat); //当前栏目
        $this->assign('locationCat', $locationCat); //当前位置
        $this->assign('topCat', $locationCat[0]); //当前最顶级栏目
        $this->assign('selfCat', $selfCat); //同级栏目
        $this->assign('sonCat', $sonCat); //下级栏目
        return $currentCat;
    }

    /**
     * 计算商品评价数量
     */
    private function staticGeval($goodsId)
    {
        $model            = new ShopGoodsGevalModel();
        $static           = [];
        $static['pic']    = $model->where('goods_id', $goodsId)->where('geval_image', 'neq', '')->count();
        $static['good']   = $model->where('goods_id', $goodsId)->where('geval_scores', 'in', [5, 4])->count();
        $static['center'] = $model->where('goods_id', $goodsId)->where('geval_scores', 'in', [3, 2])->count();
        $static['bad']    = $model->where('goods_id', $goodsId)->where('geval_scores', 'in', [1])->count();
        return $static;
    }

    /**
     * 获取评价
     */
    public function getGeval()
    {
        $goodsId = $this->request->param('goods_id');
        $level   = $this->request->param('level', 0);
        $map     = ['goods_id' => $goodsId];
        switch ($level) {
            case 1:
                $map['geval_scores'] = ['in', [5, 4]];
                break;
            case 2:
                $map['geval_scores'] = ['in', [3, 2]];
                break;
            case 3:
                $map['geval_scores'] = ['in', [1, 0]];
                break;
            case 4:
                $map['geval_image'] = ['neq', ''];
        }
        $model = new ShopGoodsGevalModel();
        $list  = $model->where($map)->paginate(12, false);

        foreach ($list as $k=>$v){
            if($v['is_anonymous']==1){
                $list[$k]['buyer_username']='匿名用户';
            }else{
                $list[$k]['buyer_username']=substr_replace($v['buyer_username'], '****', 3, 4);
            }
            $list[$k]['buyer_time']=date('Y-m-d h:i:s',$v['buyer_time']);
            $list[$k]['geval_time']=date('Y-m-d h:i:s',$v['geval_time']);
        }
        return $list;
    }

    /**
     * 计算商品价格
     * @return bool
     */
    public function calcPrice()
    {
        $goodsPrice  = $this->request->param('goods_price');
        $num         = $this->request->param('num');
        $simplePrice = $this->goodsModel->calcPrice($goodsPrice, $num);
        if ($simplePrice == false) {
            $this->error($this->goodsModel->getError());
        }
        $data = ['single_price' => $simplePrice, 'num' => $num, 'total' => $simplePrice * $num];
        return json($data);
    }

}
